/*
 * ESPackages.java - ScriptME
 * 
 * Copyright (c) 2009 Cesar Henriques <cesar at alttab.com.ar>.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Based on FESI Project
 * 
 * Contributors:
 * 	Jean-Marc Lugrin - initial API and implementation
 * 	Cesar Henriques <cesar at alttab.com.ar> - J2ME Porting and Extensions
 */
package org.scriptme.ecmascript.data;

import org.scriptme.ecmascript.exceptions.EcmaScriptException;
import org.scriptme.ecmascript.exceptions.ProgrammingError;
import org.scriptme.ecmascript.interpreter.Evaluator;
import org.scriptme.ecmascript.interpreter.LocalClassLoader;

/**
 * Implements the object loader.
 */
public class ESPackages extends ESLoader {

	/**
	 * Create the top level package loader (object Package).
	 * 
	 * @param evaluator
	 *            the evaluator
	 */
	public ESPackages(Evaluator evaluator) {
		super(evaluator);
	}

	/**
	 * Create a new package loader or package prefix.
	 * 
	 * @param packageName
	 *            The extension of the package name
	 * @param previousPackage
	 *            Represents the higher level package names
	 * @param classLoader
	 *            the class loader to use for this loader
	 * @param evaluator
	 *            the evaluator
	 */
	public ESPackages(String packageName, ESPackages previousPackage,
			LocalClassLoader classLoader, Evaluator evaluator) {
		super(packageName, previousPackage, classLoader, evaluator);
	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESLoader#getPrototype()
	 */
	public ESObject getPrototype() {
		throw new ProgrammingError("Cannot get prototype of Package");
	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESObject#getESClassName()
	 */
	public String getESClassName() {
		return "Packages";
	}

	// Utility routine to load a class
	/**
	 * Load class.
	 * 
	 * @param className
	 *            the class name
	 * 
	 * @return the class
	 * 
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 */
	private Class loadClass(String className) throws ClassNotFoundException {
		if (classLoader == null) {
			return Class.forName(className);
		} else {
			return classLoader.loadClass(className); // use our own class
														// loader
		}
	}

	// overrides
	// Getting a property dynamically creates a new Package prefix object
	// If the resulting name represents a class then the class object is created
	// and returned (and will be used for example by the "new" operator).
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESObject#getProperty(java.lang.String,
	 *      int)
	 */
	public ESValue getProperty(String propertyName, int hash)
			throws EcmaScriptException {
		ESValue value = (ESValue) properties.get(propertyName, hash);
		if (value == null) {
			String packageName = buildPrefix();
			String fullName = (packageName == null) ? propertyName
					: (packageName + "." + propertyName);

			try {
				Class cls = loadClass(fullName);
				if (debugJavaAccess) {
					System.out.println("** Class '" + fullName + "' loaded");
				}
				value = new ESWrapper(cls, evaluator);
			} catch (ClassNotFoundException e) {
				if (debugJavaAccess) {
					System.out.println("** Could not load '" + fullName
							+ "' by " + this);
					System.out.println("** Exception: " + e);
				}
				value = new ESPackages(propertyName, this, classLoader,
						evaluator);
			}

			// Cache it for faster retrievial
			properties.put(propertyName, hash, false, false, value);
		}
		return value;
	}

	// overrides
	// Establish a bean classloader
	// The parameter is the directory or jar to load from
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESObject#callFunction(org.scriptme.ecmascript.data.ESObject,
	 *      org.scriptme.ecmascript.data.ESValue[])
	 */
	public ESValue callFunction(ESObject thisObject, ESValue[] arguments)
			throws EcmaScriptException {
		if (previousPackage == null && classLoader == null) {
			// This is the Package object
			if (arguments.length < 1) {
				throw new EcmaScriptException(
						"Missing class directory or file name");
			}
			String directoryOrJar = arguments[0].toString();
			LocalClassLoader classLoader = new LocalClassLoader();
			return new ESPackages(null, null, classLoader, evaluator);
		} else {
			throw new EcmaScriptException("Java class not found: '"
					+ buildPrefix() + "'");
		}
	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESObject#getTypeofString()
	 */
	public String getTypeofString() {
		return "JavaPackage";
	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESObject#toDetailString()
	 */
	public String toDetailString() {
		return "ES:<" + getESClassName() + ":'" + buildPrefix() + "'"
				+ ((classLoader == null) ? "" : (",@" + classLoader)) + ">";
	}
}
